package com.lzx.reggie.service.impl

import com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
import com.lzx.reggie.dto.DishDto
import com.lzx.reggie.entity.Dish
import com.lzx.reggie.entity.DishFlavor
import com.lzx.reggie.mapper.DishMapper
import com.lzx.reggie.service.DishFlavorService
import com.lzx.reggie.service.DishService
import org.springframework.beans.BeanUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional


@Service
class DishServiceImpl : ServiceImpl<DishMapper, Dish>(), DishService {
    @Autowired
    private lateinit var dishFlavorService: DishFlavorService

    /**
     * 新增菜品，同时保存对应的口味数据
     * @param dishDto
     */
    @Transactional
    override fun saveWithFlavor(dishDto: DishDto) {
        //保存菜品的基本信息到菜品表dish
        save(dishDto)
        val dishId = dishDto.id //菜品id

        //菜品口味
        var flavors = dishDto.flavors
        flavors = flavors.map { item: DishFlavor ->
            item.dishId = dishId
            item
        }

        //保存菜品口味数据到菜品口味表dish_flavor
        dishFlavorService.saveBatch(flavors)
    }


    /**
     * 根据id查询菜品信息和对应的口味信息
     * @param id
     * @return
     */
    override fun getByIdWithFlavor(id: Long): DishDto {
        //查询菜品基本信息，从dish表查询
        val dish = getById(id)
        val dishDto = DishDto()

        BeanUtils.copyProperties(dish, dishDto)
        dishDto.flavors = dishFlavorService.list(
            // 查询当前菜品对应的口味信息，从dish_flavor表查询
            KtQueryWrapper(DishFlavor::class.java).apply {
                eq(DishFlavor::dishId, dish.id)
            })
        return dishDto
    }

    @Transactional
    override fun updateWithFlavor(dishDto: DishDto) {
        //更新dish表基本信息
        updateById(dishDto)

        dishFlavorService.remove(
            //清理当前菜品对应口味数据---dish_flavor表的delete操作
            KtQueryWrapper(DishFlavor::class.java).apply {
                eq(DishFlavor::dishId, dishDto.id)
            })

        //添加当前提交过来的口味数据---dish_flavor表的insert操作
        var flavors = dishDto.flavors

        flavors = flavors.map { item: DishFlavor ->
            item.dishId = dishDto.id
            item
        }
        dishFlavorService.saveBatch(flavors)
    }
}
